﻿// owner 蒋家伟

#pragma once

// qt
#include <QObject>
#include <QByteArray>
#include <QTcpSocket>

// jsdk
#include "ISocketEventHandler.h"
#include "WeakPtr.h"

namespace jsdk
{
    class SocketWorker : public QObject
    {
        Q_OBJECT
    public:
        ~SocketWorker() {};

        static OwnerPtr<SocketWorker> create(ISocketEventHandler * pSocketEventHandler);

        /// \ 当前是否work是否再工作，或者说在线
        bool isOnLine() const;

#pragma region 跨线程与ISocket的通讯信号与槽
    public slots:
        // 当前线程接受的槽，由ISocket跨线程触发
        void onConnect(QString ip, qint64 port);
        void onSend(QByteArray msg, qint64 length);

#pragma region 跨线程与ISocket的通讯信号与槽

#pragma region 当前QTcpSocket使用的信号与槽
    private slots:
        // socket触发的槽函数
        void onConnected();
        void onReadyRead();
        void onDisConnected();
        void onError(QAbstractSocket::SocketError socketError);

#pragma region 当前QTcpSocket使用的信号与槽

    private:
        bool init() const;
        SocketWorker() {};
        struct TcpSocketDeleter
        {
            void operator()(QTcpSocket*);
        };

        OwnerPtr<QTcpSocket, TcpSocketDeleter> m_opTcpSocket;
        WeakPtr<ISocketEventHandler> m_wpSocketEventHandler;
        OwnerPtr<QTcpSocket, TcpSocketDeleter> m_opTempTcpSocket;        // 此临时变量的作用，是保障了连接成功后才给真正的m_opTcpSocket赋值，而不是直接赋值再链接

        // 以下变量只用来调试使用
        std::wstring    m_ipStr;
        std::wstring    m_portStr;
    };
}